package jehc.djshi.scms.util;
import com.google.common.io.Resources;
import lombok.extern.slf4j.Slf4j;
import org.hyperic.sigar.*;

import java.io.File;

/**
 * @Desc 服务器信息监控工具类
 * @Author 邓纯杰
 * @CreateTime 2012-12-12 12:12:12
 */
@Slf4j
public class SigarUtil {

    public final static Sigar sigar = initSigar();

    private static Sigar initSigar() {
        try {
            String file = Resources.getResource("sigar/.sigar_shellrc").getFile();
            File classPath = new File(file).getParentFile();
            String path = System.getProperty("java.library.path");
            if (OSUtil.os().equals("Windows")) {
                path += ";" + classPath.getCanonicalPath();
            } else {
                path += ":" + classPath.getCanonicalPath();
            }
            System.setProperty("java.library.path", path);
            return new Sigar();
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * Swap
     * @return
     * @throws SigarException
     */
    public static Swap getSwap() throws SigarException {
        Swap swap = sigar.getSwap();
        return swap;
    }

    /**
     * 内存
     * @return
     * @throws SigarException
     */
    public static Mem getMemory() throws SigarException {
        Mem mem = sigar.getMem();
        log.info("内存总量:    " + mem.getTotal() / 1024L + "K av");// 内存总量
        log.info("当前内存使用量:    " + mem.getUsed() / 1024L + "K used");// 当前内存使用量
        log.info("当前内存剩余量:    " + mem.getFree() / 1024L + "K free");// 当前内存剩余量
        return mem;
    }

    /**
     * 获取CPU信息
     * @return
     * @throws SigarException
     */
    public static CpuInfo[] getCpuInfoList() throws SigarException{
       return sigar.getCpuInfoList();
    }

    /**
     * cpu
     * @return
     * @throws SigarException
     */
    public static CpuPerc getCpu() throws SigarException {
        CpuPerc perc = sigar.getCpuPerc();
        log.info("整体cpu的占用情况:");
        log.info("空闲率: " + CpuPerc.format(perc.getIdle()));//获取当前cpu的空闲率
        log.info("占用率: "+ CpuPerc.format(perc.getCombined()));//获取当前cpu的占用率
        return perc;
    }

    /**
     * 磁盘分区
     * @throws Exception
     */
    public static void file() throws Exception {
        FileSystem fslist[] = sigar.getFileSystemList();
        for (int i = 0; i < fslist.length; i++) {
            log.info("分区的盘符名称" + i);
            FileSystem fs = fslist[i];
            log.info("盘符名称:    " + fs.getDevName());// 分区的盘符名称
            log.info("盘符路径:" + fs.getDirName());// 分区的盘符名称
            log.info("盘符标志:" + fs.getFlags());//盘符标志
            log.info("盘符类型:" + fs.getSysTypeName());// 文件系统类型，比如 FAT32、NTFS
            log.info("盘符类型名:" + fs.getTypeName());// 文件系统类型名，比如本地硬盘、光驱、网络文件系统等
            log.info("盘符文件系统类型:" + fs.getType()); // 文件系统类型
            FileSystemUsage usage = null;
            usage = sigar.getFileSystemUsage(fs.getDirName());
            log.info(fs.getDevName() + "读出：" + usage.getDiskReads());
            log.info(fs.getDevName() + "写入：" + usage.getDiskWrites());
        }
        return;
    }

    /**
     * 网络
     * @param ip
     * @return
     * @throws Exception
     */
    public float[] net(String ip) throws Exception{
         float[] result = {0f,0f};
        if(netBytes(ip) == null) return result;

        long time  = System.currentTimeMillis();
        long rx = netBytes(ip).getRxBytes();
        long tx = netBytes(ip).getTxBytes();
        Thread.sleep(500);

        time  = System.currentTimeMillis()-time;
        rx = netBytes(ip).getRxBytes()-rx;
        tx = netBytes(ip).getTxBytes()-tx;
        result[0] = rx*1f/time;//kb/sec
        result[1] = tx*1f/time;
        return result;
    }

    /**
     *
     * @param ip
     * @return
     * @throws Exception
     */
    public static NetInterfaceStat netBytes(String ip) throws Exception {
        String ifNames[] = sigar.getNetInterfaceList();
        NetInterfaceStat result = null;
        for (int i = 0; i < ifNames.length; i++) {
            String name = ifNames[i];
            NetInterfaceConfig ifconfig = sigar.getNetInterfaceConfig(name);
            if(ifconfig.getAddress().equals(ip)){
                result = sigar.getNetInterfaceStat(name);
                break;
            }
            log.info("网络设备名: " + name);// 网络设备名
            log.info("IP地址: " + ifconfig.getAddress());// IP地址
            log.info("子网掩码:" + ifconfig.getNetmask());// 子网掩码
            if ((ifconfig.getFlags() & 1L) <= 0L) {
                log.info("!IFF_UP...skipping getNetInterfaceStat");
                continue;
            }
            NetInterfaceStat ifstat = sigar.getNetInterfaceStat(name);
            log.info(name + "接收的总包裹数:" + ifstat.getRxPackets());// 接收的总包裹数
            log.info(name + "发送的总包裹数:" + ifstat.getTxPackets());// 发送的总包裹数
            log.info(name + "接收到的总字节数:" + ifstat.getRxBytes());// 接收到的总字节数
            log.info(name + "发送的总字节数:" + ifstat.getTxBytes());// 发送的总字节数
            log.info(name + "接收到的错误包数:" + ifstat.getRxErrors());// 接收到的错误包数
            log.info(name + "发送数据包时的错误数:" + ifstat.getTxErrors());// 发送数据包时的错误数
            log.info(name + "接收时丢弃的包数:" + ifstat.getRxDropped());// 接收时丢弃的包数
            log.info(name + "发送时丢弃的包数:" + ifstat.getTxDropped());// 发送时丢弃的包数
        }
        return result;
    }
}
